package com.jilintongyi.jlcrtvu.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import com.jilintongyi.jlcrtvu.security.LoginFailureHandler;
import com.jilintongyi.jlcrtvu.security.LoginSuccessHandler;
import com.jilintongyi.jlcrtvu.security.LogoutSuccessHandler;
import com.jilintongyi.jlcrtvu.service.impl.UserDetailsServiceImpl;

/**
 * 安全框架配置
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法级别的权限控制 @PreAuthorize
public class SecurityConfig {
	@Autowired
	private UserDetailsServiceImpl userDetailsService;
	@Autowired
	private LoginSuccessHandler loginSuccessHandler;
	@Autowired
	private LogoutSuccessHandler logoutSuccessHandler;
	@Autowired
	private LoginFailureHandler loginFailureHandler;

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http.csrf().disable(); // 关闭csrf
		http.authorizeHttpRequests().antMatchers("/admin/**").authenticated().anyRequest()
				.permitAll(); // admin路径全部需要认证，其他路径全部允许访问。
		http.formLogin().loginPage("/login") // 登录页面
				.successHandler(loginSuccessHandler) // 登录成功处理
				.failureHandler(loginFailureHandler); // 登录失败处理
		http.rememberMe().tokenValiditySeconds(60 * 60 * 24 * 7); // 记住我的有效期为一周
		http.userDetailsService(userDetailsService); // 用户详情服务
		http.logout() // 登出
				.logoutSuccessHandler(logoutSuccessHandler); // 登出成功处理
		return http.build();
	}

	/**
	 * 密码加密器
	 * 
	 * @return
	 */
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder(); // 密码加密方式 123456 =
											// $2a$10$lXCErO3rG3yVhowkVuVec.qooi2WqxNarqhSNnM916NLeqY/Vry5K
	}
}
